import React from 'react';
import { Button, Icon, message, Modal, Tooltip } from 'antd';
import {WeaErrorPage, WeaTools, WeaNewScroll, WeaInputSearch, WeaBrowser, WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import { dragBaseElement } from '../util/rcmenu';
class HpBaseElement extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            value: '',
            addFinish: true, 
        }
        this.handleOnShow = this.handleOnShow.bind(this);
        this.handleAddElement = this.handleAddElement.bind(this);
        this.onAdd = this.onAdd.bind(this);
        this.handleOnSearch = this.handleOnSearch.bind(this);
        this.onSave = this.onSave.bind(this);
    }
    handleOnShow(){
        this.refs.ElementTemplate.onShow();
    }
    handleAddElement(ebaseid, areaflag = 'A', index = 0){
        if(!this.state.addFinish) return;
    	if($("#e9PortalSetting").find(".item").length === 10) {
            Modal.confirm({
                title: getLabel(15172,"系统提示"),
                content:getLabel(84090,"继续添加会影响页面性能，还要继续吗？"),
                onOk:() => {
                    this.onAdd(ebaseid, areaflag, index);
                }
            });
    	}else{
    		this.onAdd(ebaseid, areaflag, index);
    	}
    }
    onAdd(ebaseid, areaflag, index){
        let { params, handleAddStart, handleAdd } = this.props;
        const { hpid, isSetting } = params;
        params.ebaseid = ebaseid;
        params.areaflag = areaflag;
        params.index = index;
        this.setState({
            addFinish: false,
        });
        handleAddStart();
        WeaTools.callApi('/api/portal/hpbaseelement/addElement', 'POST', params).then((data) => {
            if(data.status === '2'){
                message.error(data.errormsg,2);
            }else{
                this.setState({
                    addFinish: true,
                });
                try{
                    handleAdd(data, areaflag, index);
                } catch(e){
                    window.console ? console.log(getLabel(387990,"添加元素后刷新门户异常："),e) : alert(getLabel(387990,"添加元素后刷新门户异常：")+e);
                }
            }
        });
    }
    handleOnSearch(value){
        this.setState({
            value,
        });
    }
    render(){
        const { isSynergySetting, list, params, handleRefreshPortal } = this.props;
        const { hpid, subCompanyId } = params;
        let pageType = (subCompanyId == '-1' || subCompanyId == '') ?  '1' : '2';
        let { value } = this.state;
        //特殊处理抽藏元素（zang）多音字
        if(value == 'sc') value = 'sz';
        else if(value == 'scy') value = 'szy';
        else if(value == 'scys') value = 'szys';
        let htmlArr = new Array;
        list.map((item)=>{
            if(value && item.title.toLowerCase().indexOf(value.toLowerCase()) == -1 && item.id.toLowerCase() !== value.toLowerCase() && item.pinyin.toLowerCase().indexOf(value.toLowerCase()) == -1){
                return;
            }
            htmlArr.push(
                <div className="portal-setting-left-hpbaseelement-item"  title={item.title} onMouseDown={dragBaseElement.bind(this,item.id, this.handleAddElement)}>
                    <div className="portal-setting-left-hpbaseelement-icon">
                        <img src={item.icon} alt='' onError={e =>e.target.src = '/spa/portal/images/icon-element.png'}/>
                    </div>
                    <div className="portal-setting-left-hpbaseelement-name">
                        <span onClick={this.handleAddElement.bind(this,item.id,'A',0)}>{item.title}</span>
                    </div>
                </div>
            );
        });
        return <div className="portal-setting-left-hpbaseelement">
            <div className="portal-setting-left-hpbaseelement-addElement">
                <div className="portal-setting-left-hpbaseelement-search" style={{width: isSynergySetting ? '140px' :'110px'}}>
                    <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@juggte`} onSearchChange={this.handleOnSearch} />
                </div>
                {
                    !isSynergySetting ? (
                            <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@4uqaje`}
                                tabs={[
                                    {name: getLabel(387984,"已有元素"),
                                        key: '1',
                                        dataParams: {sourcetype: '1', pageType: pageType},
                                        browserProps:{conditionDataParams: {sourcetype: '1', pageType: pageType}}
                                    },
                                    {
                                        name: getLabel(386539, '元素模板'),
                                        key: '2', selected: true,
                                        dataParams: {sourcetype: '2', pageType: pageType},
                                        browserProps: {conditionDataParams: {sourcetype: '2', pageType: pageType}}
                                    }
                                    ]}
                                type={'element'}
                                inputStyle={{width:'373px',marginLeft:'15px'}}
                                title={getLabel(386382, "请选择")}
                                isSingle={false}
                                icon='icon-coms-portal'
                                iconBgcolor='#1a57a0'
                                customized
                                hasTabConditions
                                onChange={this.onSave}
                            >
                                <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@sj6gln`} placement="right" title={getLabel(32385,"从模板导入")}>
                                    <div className="portal-setting-left-hpbaseelement-template">
                                        <i className="icon-coms-leading-in"/>
                                    </div>
                                </Tooltip>
                            </WeaBrowser>
                        ) : ''
                }
            </div>
            <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@6p2mpe`} scrollId="hpbaseelement" height="100%">{htmlArr}</WeaNewScroll>
        </div>
    }
    onSave(ids){
        const { params, handleRefreshPortal } = this.props;
        if(ids !=''){
            WeaTools.callApi('/api/portal/elementtemplateadd/save', 'POST', {
                areaflag: 'A',
                ...params,
                ids,
            }).then(result => {
                if(status == '2'){
                    message.error(result.errormsg);
                    return;
                }
                message.success(getLabel(83880,"添加成功！"));
                handleRefreshPortal();
            });
        }
    }
}
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
            return ( <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@reslar`} msg = { hasErrorMsg ? this.props.error : getLabel(385218,"对不起，该页面异常，请联系管理员！") }/>
        );
    }
}

HpBaseElement = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(HpBaseElement);
export default HpBaseElement;
